package com.salesmanager.license.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

public final class LicenseUtil {

	private static String getHostName() throws UnknownHostException {
		return InetAddress.getLocalHost().getHostAddress();
	}

	private static String getMACAddress() throws UnknownHostException,
			SocketException {
		// NetworkInterface network =
		// NetworkInterface.getByInetAddress(InetAddress.getLocalHost());
		List<NetworkInterface> networks = Collections.list(NetworkInterface
				.getNetworkInterfaces());

		byte[] mac = networks.get(0).getHardwareAddress();
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < mac.length; i++) {
			sb.append(String.format("%02X%s", mac[i],
					(i < mac.length - 1) ? "-" : ""));
		}
		return sb.toString();
	}

	private static String getSecureLicense(String passwordToHash) {
		String generatedPassword = null;
		try {
			// Create MessageDigest instance for MD5
			MessageDigest md = MessageDigest.getInstance("MD5");
			// Add password bytes to digest
			byte[] bytes = md.digest(passwordToHash.getBytes());
			// This bytes[] has bytes in decimal format;
			// Convert it to hexadecimal format
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < bytes.length; i++) {
				sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16)
						.substring(1));
			}
			// Get complete hashed password in hex format
			generatedPassword = sb.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return generatedPassword;
	}

	public static boolean checkLicense(String license)
			throws UnknownHostException, SocketException {
		if (license == null)
			return false;
		String checkString = getlicense(getKey()).trim();
		if (license.equals(checkString)) {
			return true;
		}
		return false;
	}

	public static boolean checkTrailLicense(String license)
			throws UnknownHostException, SocketException {
		if (license == null)
			return false;
		String checkString = getTrailLicense(getKey()).trim();
		if (license.equals(checkString)) {
			return true;
		}
		return false;
	}

	public static String getlicense(String key) throws UnknownHostException,
			SocketException {
		return getSecureLicense(key + "longhai");
	}

	public static String getTrailLicense(String key) throws UnknownHostException,
			SocketException {
		return getSecureLicense(key + "longhai_trail");
	}

	public static String getKey() throws UnknownHostException, SocketException {
		return getSecureLicense(MiscUtils.getMotherboardSN()
				+ MiscUtils.getSerialNumber("D"));
	}
}
